package org.jeecg.modules.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.jeecg.modules.entity.DbContract;
import org.jeecg.modules.entity.DbDelivery;
import org.jeecg.modules.entity.dto.DbDeliveryDto;
import org.jeecg.modules.mapper.DbDeliveryMapper;
import org.jeecg.modules.service.IDbContractService;
import org.jeecg.modules.service.IDbDeliveryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: db_delivery
 * @Author: jeecg-boot
 * @Date:   2024-06-26
 * @Version: V1.0
 */
@Service
public class DbDeliveryServiceImpl extends ServiceImpl<DbDeliveryMapper, DbDelivery> implements IDbDeliveryService {


    @Autowired
    private IDbContractService dbContractService;
    /**
     * 批量修改
     * @param dbDeliveryDto
     * @return
     */
    @Transactional
    public void updateByIds(DbDeliveryDto dbDeliveryDto) {
        UpdateWrapper<DbDelivery> dbDeliveryUpdateWrapper = new UpdateWrapper<>();
//        修改交付状态
        dbDeliveryUpdateWrapper.set("complete",dbDeliveryDto.getComplete())
                .in("id",dbDeliveryDto.getIds());
        this.update(dbDeliveryUpdateWrapper);
//        查找最新交付进度
        QueryWrapper<DbDelivery> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contract_id",dbDeliveryDto.getContractId())
                .eq("complete",1)
                .eq("deleted",0)
                .orderByDesc("progress");
        List<DbDelivery> list = this.list(queryWrapper);
//        如果交付进度状态为空，则更新合同交付进度为0
        if (list == null || list.isEmpty()){
            UpdateWrapper<DbContract> dbContractUpdateWrapper = new UpdateWrapper<>();
            dbContractUpdateWrapper.set("delivery_progress",0)
                    .eq("contract_id",dbDeliveryDto.getContractId());
            dbContractService.update(dbContractUpdateWrapper);
        }
//        获取最大的交付进度，更新合同交付进度
        else {
            DbDelivery dbDelivery = list.get(0);
            UpdateWrapper<DbContract> dbContractUpdateWrapper = new UpdateWrapper<>();
            dbContractUpdateWrapper.set("delivery_progress",dbDelivery.getProgress())
                    .eq("contract_id",dbDeliveryDto.getContractId());
            dbContractService.update(dbContractUpdateWrapper);
        }

    }
}
